
// 引入状态码statusCode

const statusCode = require('./statusCode')
// 定义请求路径, BASEURL: 普通请求API; CBASEURL: 中台API,不使用中台可不引入CBASEURL
const { BASEURL } = require('./config')
// 定义默认参数
const defaultOptions = {
  data: {},
  ignoreToken: false,
  form: false,
  headers:null
}

function startLoading() {
  wx.showLoading({
    title: '加载中...',
    icon: 'none'
  })
}
function endLoading() {
  wx.hideLoading();
}
// 声明一个对象用于存储请求个数
var needLoadingRequestCount = 0;
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
};
/**
 * 发送请求
 * @params
 * method: <String> 请求方式: POST/GET
 * url: <String> 请求路径
 * data: <Object> 请求参数
 * ignoreToken: <Boolean> 是否忽略token验证
 * form: <Boolean> 是否使用formData请求
 */
function request (options) {

  let DOptions = JSON.parse(JSON.stringify(defaultOptions))
  let _options = Object.assign(DOptions, options)
  let { method, url, data, ignoreToken, form ,headers} = _options
  const app = getApp()
  console.log("defaultOptions------header--111-->",_options)
  // 设置请求头
  let header = {}
  if (!headers) {
    header = {
      'content-type': 'application/json' //自定义请求头信息
    }
  } else {
    header = headers
  }

  showFullScreenLoading();
  // if (!ignoreToken) {
  //   // 从全局变量中获取token
  //   let token = app.globalData.token
  //   header.Authorization = `Bearer ${token}`
  // }
  header['Authorization'] = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImY3ZWJmZTgyLWZhZjYtNDk2ZS05ZDNhLTkzNzU1ZGQwOGNjYyJ9.y9bQzt1iLi1_ItcFmVP_Jys0mxa039jsuSkWOhqt44BeUb-35HDErupPtOhsgm_nrq-jlHR5Us3Ke_1KRVeiwg"
  return new Promise((resolve, reject) => {
  
    wx.request({
      url: BASEURL + url,
      data,
      header,
      method,
      success: (res) => {
        let { code ,data} = res.data
        tryHideFullScreenLoading();
        if (code === statusCode.SUCCESS) {
          // if (res.data.code !== 0) {
          //   // 统一处理请求错误
          //   showToast(res.data.errorMsg)
          //   reject(res.data)
          //   return
          // }
          resolve(data)
        } else if (code === statusCode.EXPIRE) {
          app.globalData.token = ''
          showToast(`登录过期, 请重新刷新页面`)
          reject(data)
        } else {
          console.log("res--------11----xx--res.data-->",res.data)
          showToast(res.data.msg || '网络异常')
          reject(data)
        }
      },
      fail: (err) => {
        tryHideFullScreenLoading();
        console.log('%c err', 'color: red;font-weight: bold', err)
        showToast(err.msg)
        reject(err)
      }
    })
  })
}

// 封装toast函数
function showToast (title, icon='none', duration=800, mask=false) {
  wx.showToast({
    title: title || '',
    icon,
    duration,
    mask
  });
}

function get (options) {
  return request({
    method: 'GET',
    ...options
  })
}

function post (options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: 'POST',
    ...options
  })
}

export default request